<template>
  <div style="height: 100%;">
    <crud-table ref="crudTableRef" :config="dictConfig">
    <!-- 添加导入按钮到表格头部 -->
    <template #table-header-left>
      <n-button 
        @click="handleImport"
        class="custom-button"
        quaternary
      >
        <template #icon>
          <n-icon>
            <import-outlined />
          </n-icon>
        </template>
        导入
      </n-button>
    </template>
  </crud-table>

  <!-- 排序弹窗 -->
  <n-modal
      :mask-closable="false"
    v-model:show="showSortModal"
    preset="card"
    title="排序管理"
    style="width: 600px"
    size="small"
  >
    <n-scrollbar style="max-height: 500px">
      <draggable
        v-model="sortableData"
        item-key="id"
        :animation="150"
        class="sort-list"
      >
        <template #item="{ element }">
          <div class="sort-item">
            <n-icon size="20" class="drag-handle">
              <drag-outlined />
            </n-icon>
            <span>{{ element.dict_value }}</span>
          </div>
        </template>
      </draggable>
    </n-scrollbar>
    <template #footer>
      <n-space justify="end">
        <n-button @click="showSortModal = false">取消</n-button>
        <n-button type="primary" :loading="sortLoading" @click="handleSortSubmit">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>

  <!-- 导入弹窗 -->
  <n-modal
    v-model:show="showImportModal"
    :mask-closable="false"
    preset="card"
    title="导入字典"
    style="width: 600px"
    size="small"
  >
    <n-form
      ref="importFormRef"
      :model="importForm"
      :rules="importRules"
      label-placement="left"
      label-width="100"
      require-mark-placement="right-hanging"
    >
      <n-form-item label="上级字典" path="parent_id">
        <n-select
          v-model:value="importForm.parent_id"
          :options="dictOptions"
          placeholder="请选择上级字典"
          clearable
        />
      </n-form-item>
      <n-form-item label="Excel文件" path="file">
        <n-upload
          accept=".xlsx,.xls"
          :default-upload="false"
          :max="1"
          @change="handleUploadChange"
        >
          <n-button>选择文件</n-button>
        </n-upload> 
      </n-form-item>
      <n-form-item label="下载模板">
        <n-space vertical>
          <n-button type="primary" @click="downloadTemplate">
            下载导入模板
          </n-button>
          <span>请按模板格式填写：键名和键值为必填项</span>
        </n-space>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="showImportModal = false">取消</n-button>
        <n-button
          type="primary"
          :loading="importLoading"
          :disabled="!importForm.file"
          @click="handleImportSubmit"
        >
          确定导入
        </n-button>
      </n-space>
    </template>
  </n-modal>
  </div>
</template>

<script setup>
import { h, ref, onMounted } from 'vue'
import { NTag, NInputNumber, NButton, NSpace, useMessage, NModal, NScrollbar, NIcon, NForm, NFormItem, NSelect, NUpload } from 'naive-ui'
import draggable from 'vuedraggable'
import moment from 'moment'
import ImageUpload from '@/components/ImageUpload/index.vue'
import request from '@/utils/request'
import {
  PlusOutlined,
  DragOutlined,
  ImportOutlined
} from "@vicons/antd"

const message = useMessage();
// 获取字典列表作为选项
const getDictOptions = async () => {
  try {
    const res = await request.get('/dictionaries')
    return res.map(item => ({
      label: item.dict_value,
      value: item.id
    }))
  } catch (error) {
    return []
  }
}
const dict_type = [
  {
    label:'业务字典',
    value:'business'
  },
  {
    label:'系统字典',
    value:'system'
  }
]
const crudTableRef = ref(null)
// 处理添加子项
const handleAddChild = (row) => {
  crudTableRef.value?.handleAddChild(row, {
    dict_type: row.dict_type // 继承父级的字典类型
  })
}
// 处理排序
const showSortModal = ref(false)
const sortableData = ref([])
const sortLoading = ref(false)

// 处理打开排序弹窗
const handleSortChild = (row) => {
  // 获取当前字典的子项列表
  sortableData.value = row.dictionary_details || []
  showSortModal.value = true
}

// 导入相关
const showImportModal = ref(false)
const importLoading = ref(false)
const importFormRef = ref(null)
const importForm = ref({
  parent_id: null,
  file: null
})

// 导入表单验证规则
const importRules = {
  parent_id: {
    required: true,
    message: '请选择上级字典'
  },
  file: {
    required: true,
    message: '请选择Excel文件',
    validator: (rule, value) => {
      if (!value) return true
      const fileName = value.file?.name || ''
      const isExcel = /\.(xlsx|xls)$/.test(fileName.toLowerCase())
      if (!isExcel) {
        return new Error('只支持.xlsx、.xls格式的Excel文件')
      }
      return true
    }
  }
}

// 字典选项
const dictOptions = ref([])

// 获取字典选项
const fetchDictOptions = async () => {
  try {
    const res = await request.get('/dictionaries')
    dictOptions.value = res.map(item => ({
      label: item.dict_value,
      value: item.id
    }))
  } catch (error) {
    message.error('获取字典列表失败')
  }
}

// 处理文件上传改变
const handleUploadChange = ({ file }) => {
  const fileName = file.file?.name || ''
  const isExcel = /\.(xlsx|xls)$/.test(fileName.toLowerCase())
  
  if (!isExcel) {
    message.error('只支持.xlsx、.xls格式的Excel文件')
    return
  }
  
  importForm.value.file = file
}

// 修改下载模板功能
const downloadTemplate = async () => {
  try {
    // 创建模板数据
    const templateData = [
      ['键名', '键值'],
      ['示例名称1', 'example_key1'],
      ['示例名称2', 'example_key2']
    ]
    
    // 使用 XLSX 库创建工作簿
    const XLSX = await import('xlsx')
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(templateData)
    
    // 设置列宽
    ws['!cols'] = [
      { wch: 20 }, // 键名列宽
      { wch: 20 }  // 键值列宽
    ]
    
    XLSX.utils.book_append_sheet(wb, ws, '字典导入模板')
    
    // 生成Excel文件并下载
    XLSX.writeFile(wb, '字典导入模板.xlsx')
  } catch (error) {
    message.error('模板下载失败')
  }
}

// 处理导入提交
const handleImportSubmit = async () => {
  try {
    await importFormRef.value?.validate()
    importLoading.value = true
    
    const formData = new FormData()
    formData.append('file', importForm.value.file.file)
    formData.append('parent_id', importForm.value.parent_id)
    
    await request.post('/dictionary-details/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    message.success('导入成功')
    showImportModal.value = false
    crudTableRef.value?.fetchData()
  } catch (error) {
    if (error?.message) {
      message.error(error.message)
    }
  } finally {
    importLoading.value = false
  }
}

// 打开导入弹窗
const handleImport = async () => {
  await fetchDictOptions()
  showImportModal.value = true
}

const dictConfig = ref({
  title: '字典管理',
  apiPrefix: '/dictionaries',
  primaryKey: 'id',
  searchable: false,

  creatable: true,
  editable: true,
  deletable: true,

  // 子项配置
  childConfig: {
    apiPrefix: '/dictionary-details',
    parentField: 'parent_id',
    childrenKey: 'dictionary_details',
    formFields: [
      {
        label: '字典键名',
        key: 'dict_value',
        type: 'input',
        span: 24,
        rules: [{ required: true, message: '请输入字典键名' }]
      },
      {
        label: '字典键值',
        key: 'dict_key',
        type: 'input',
        span: 24,
        rules: [{ required: true, message: '请输入字典键值' }]
      },

      {
        label: '图标',
        key: 'icon',
        type: 'custom',
        span: 24,
        render: ({ value, onChange }) => {
          return h(ImageUpload, {
            value,
            'onUpdate:value': onChange
          })
        }
      },
      {
        label: '描述',
        key: 'description',
        type: 'textarea',
        span: 24
      }
    ]
  },

  // 表格配置
  tableConfig: {
    childrenKey: 'dictionary_details',
    defaultExpandAll: true,
    pagination: false,
    bordered: false,
    size: 'medium',
    indent: 20,
    scrollX: 1600
  },

  // 表格列配置
  columns: [
    {
      title: '字典名称',
      key: 'dict_value', 
      sortable: true,
      ellipsis: true,
      fixed: 'left' // 固定左侧
    },
    {
      title: '字典键名',
      key: 'dict_key', 
      sortable: true,
      ellipsis: true
    },
    {
      title: '图标',
      key: 'icon', 
      render: (row) => {
        return h('div', { style: 'display: flex; align-items: center; gap: 4px;' }, [
          // 显示当前图标
          row.icon ? h('img', {
            src: row.icon,
            style: {
              width: '24px',
              height: '24px',
              borderRadius: '4px',
              objectFit: 'cover'
            }
          }) : null,
          // 使用更新后的上传组件
          h(ImageUpload, {
            value: row.icon,
            size: 50,
            compact: true, // 启用紧凑模式
            'onUpdate:value': async (url) => {
              try {
                if (url === row.icon) return
                
                const apiUrl = row.parent_id 
                  ? `/dictionary-details/${row.id}`
                  : `/dictionaries/${row.id}`
                
                await request.put(apiUrl, {
                  icon: url
                })
                
                message.success('图标更新成功')
                crudTableRef.value?.fetchData()
              } catch (error) {
                message.error('图标更新失败')
              }
            }
          })
        ])
      }
    },
    {
      title: '字典类型',
      key: 'dict_type', 
      ellipsis: true,
      render: (row) => {
        // 如果没有字典类型,返回空
        if (!row.dict_type) return null

        const typeMap = {
          business: {
            type: 'info',
            label: '业务字典'
          },
          system: {
            type: 'warning',
            label: '系统字典'
          }
        }

        const config = typeMap[row.dict_type] || {
          type: 'default',
          label: row.dict_type
        }

        return h(NTag, {
          type: config.type,
          size: 'small',
          round: true,
          bordered: false
        }, {
          default: () => config.label
        })
      }
    },

    {
      title: '描述',
      key: 'description', 
      ellipsis: true
    },
    {
      title: '创建时间',
      key: 'created_at', 
      sortable: true,
      render: (row) => {
        return row.created_at && moment(row.created_at).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  ],

  // 父级表单配置
  formFields: [
    {
      label: '字典名称',
      key: 'dict_value',
      type: 'input',
      span: 24,
      rules: [{ required: true, message: '请输入字典名称' }]
    },
    {
      label: '字典键名',
      key: 'dict_key',
      type: 'input',
      span: 24,
      rules: [{ required: true, message: '请输入字典键名' }]
    },
    {
      label: '字典类型',
      key: 'dict_type',
      type: 'select',
      options: dict_type,
      span: 24,
      update_disabled: true,
      rules: [{ required: true, message: '请选择字典类型' }]
    },
    {
      label: '图标',
      key: 'icon',
      type: 'custom',
      span: 24,
      render: ({ value, onChange }) => {
        return h(ImageUpload, {
          value,
          'onUpdate:value': onChange
        })
      }
    },
    {
      label: '描述',
      key: 'description',
      type: 'textarea',
      span: 24
    }
  ],

  // 表单验证规则
  rules: {
    dict_value: { required: true, message: '请输入字典名称' },
    dict_key: { required: true, message: '请输入字典键名' },
    dict_type: { required: true, message: '请输入字典类型' }
  },

  // 子项表单配置
  detailForm: {
    title: '字典子项',
    apiPrefix: '/dictionary-details',
    formFields: [
      {
        label: '上级字典',
        key: 'parent_id',
        type: 'select',
        span: 24,
        options: getDictOptions
      },
      {
        label: '字典名称',
        key: 'dict_value',
        type: 'input',
        span: 12
      },
      {
        label: '字典键名',
        key: 'dict_key',
        type: 'input',
        span: 12
      },

      {
        label: '图标',
        key: 'icon',
        type: 'custom',
        span: 24,
        render: ({ value, onChange }) => {
          return h(ImageUpload, {
            value,
            'onUpdate:value': onChange
          })
        }
      },
      {
        label: '描述',
        key: 'description',
        type: 'textarea',
        span: 24
      }
    ],
    rules: {
      parent_id: { required: true, message: '请选择上级字典' },
      dict_value: { required: true, message: '请输入字典名称' },
      dict_key: { required: true, message: '请输入字典键名' }
    }
  },

  // 自定义操作按钮配置
  customActions: [
    {
      label: '排序',
      type: 'primary',
      size: 'small',
      show: (row) => !row.parent_id,
      quaternary: true,
      icon: () => h(DragOutlined),
      onClick: handleSortChild
    },
    {
      label: '添加',
      type: 'primary',
      size: 'small',
      show: (row) => !row.parent_id,
      quaternary: true,
      icon: () => h(PlusOutlined),
      onClick: handleAddChild
    }
  ]
})

// 处理排序提交
const handleSortSubmit = async () => {
  try {
    sortLoading.value = true

    // 构建排序数据
    const sortData = sortableData.value.map((item, index) => ({
      id: item.id,
      sort: index + 1
    }))

    // 调用批量排序接口
    await request.put('/dictionary-details/batch-sort', {
      items: sortData
    })

    message.success('排序更新成功')
    showSortModal.value = false

    // 刷新表格数据
    crudTableRef.value?.fetchData()
  }  finally {
    sortLoading.value = false
  }
}

onMounted(async () => {
  // 获取并打印原始数据
  const data = await request.get('/dictionaries')
  console.log('Dictionary Data:', data)
})

</script>

<style scoped>
.n-tree {
  margin-top: 16px;
}
.n-tree :deep(.n-tree-node-content) {
  padding: 4px 0;
}
.n-tree :deep(.n-tree-node-content__text) {
  flex: 1;
}

.sort-list {
  padding: 8px;
  position: relative;
}

/* 拖拽项样式 */
.sort-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: move; /* 整个元素都显示移动光标 */
  transition: all 0.3s;
  position: relative;
  user-select: none; /* 防止文本被选中 */
}

.sort-item:hover {
  background: #f5f5f5;
  border-color: #2080f0;
  box-shadow: 0 2px 6px rgba(32, 128, 240, 0.1);
}

.sort-item .drag-handle {
  margin-right: 12px;
  color: #999;
  pointer-events: none; /* 图标不再响应鼠标事件 */
}

.sort-item:hover .drag-handle {
  color: #2080f0;
}

/* 拖动时的样式 */
.sortable-ghost {
  opacity: 0;
  background: transparent;
  border: 2px dashed #2080f0;
}

.sortable-ghost::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #2080f0;
  top: -1px;
}

/* 选中项样式 */
.sortable-chosen {
  background: #fff;
  border-color: #2080f0;
  box-shadow: 0 4px 12px rgba(32, 128, 240, 0.15);
  transform: scale(1.02);
  z-index: 2;
}

/* 拖动时的占位样式 */
.sortable-drag {
  opacity: 0.9;
  background: #fff;
  box-shadow: 0 8px 16px rgba(32, 128, 240, 0.15);
  transform: rotate(1deg) scale(1.02);
}

/* 列表项内容样式 */
.sort-item span {
  flex: 1;
  margin-left: 8px;
  font-size: 14px;
  color: #333;
  pointer-events: none; /* 文本不响应鼠标事件 */
}

/* 添加动画效果 */
.sort-list > * {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.custom-button {
  margin-right: 12px;
}
</style>
